package com.brickworkers.codemaker.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

import com.brickworkers.codemaker.domain.Row.Builder;
import com.brickworkers.codemaker.domain.Table;
import com.brickworkers.codemaker.enums.BuilderType;
import com.brickworkers.codemaker.utils.PathUtil;

import static com.brickworkers.codemaker.utils.MakerconfResource.rb;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FileWriterService {
	Writer out = null;

	
	public void fileWriter(){
		for (BuilderType builderType : BuilderType.values()) {
			fileWriter(rb.getString(builderType.getDescription()), rb.getString(builderType.getToFilePath()), builderType.getSuffix());
		}
		
	}
	
	private void fileWriter(String templateName, String outFilePath, String fileSuffix){
		Configuration cfg;
		try {
			cfg = FileOutPutFactory.getConf();
			Template template = cfg.getTemplate(templateName);
			List<Table> tables = new TableMessageService().getTables();
			for (Table table : tables) {
				//插入对应的包名
				table.setPackageName(outFilePath);
				System.out.println("src/main/java/"+outFilePath.replace(".", "/") +"/"+table.getClassName()+ fileSuffix);
				String url = "src/main/java/"+outFilePath.replace(".", "/") +"/";
				//如果文件路径不存在就创建一个
				File file = new File(url);
				file.mkdirs();
				out = new FileWriter(url+table.getClassName()+ fileSuffix);
				template.process(table, out);
			}
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
